//
//  MTCSearchContractViewController.m
//  ERP
//
//  Created by QA on 15/10/23.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MTCSearchContractViewController.h"
#import "MJRefresh.h"
#import "MTContractListViewCell.h"
#import "UITableView+Custom.h"
#import "NSKeyedArchiverUserLogin.h"

#import "NSDictionary+DataFormat.h"
#import "WebServiceCommonRequest.h"

#import "MTCContractDetailViewController.h"

@interface MTCSearchContractViewController ()

@property (strong, nonatomic) NSMutableArray *resultData;
@property (assign, nonatomic) NSInteger segmentActionState;

@end

@implementation MTCSearchContractViewController
//@synthesize segmentedView = _segmentedView;
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"合同搜索"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    self.tableView.tableHeaderView = self.searchView;
    [self.tableView setTableViewNotDataDrawText:@"请选择或者输入搜索信息" isShow:YES];
    
    [self.searchField addTarget:self action:@selector(eventsSearch:) forControlEvents:UIControlEventEditingChanged];
    [self.HTXZSegmente addTarget:self action:@selector(eventsSearch:) forControlEvents:UIControlEventValueChanged];
    [self.HTZTSegmente addTarget:self action:@selector(eventsSearch:) forControlEvents:UIControlEventValueChanged];
    [self.FFZTSegmente addTarget:self action:@selector(eventsSearch:) forControlEvents:UIControlEventValueChanged];
    [self.SHZTSegmente addTarget:self action:@selector(eventsSearch:) forControlEvents:UIControlEventValueChanged];
}

//返回事件
- (void)backButtonEvent:(id)sender
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark IBAction

- (void)eventsSearch:(id)sender
{
    [self headerRereshing];
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.tableView footerEndRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

//具体委托方法实例
-(void)segmentAction:(UISegmentedControl *)Seg
{
    NSInteger index = Seg.selectedSegmentIndex;
    self.segmentActionState = index;
    
    [self.resultData removeAllObjects];
    [self.tableView reloadData];
    [self.tableView headerBeginRefreshing];
}

#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //数据清理
    if(isReresh) [self.resultData removeAllObjects];
    [self.tableView reloadData];
    if(isReresh)[self.tableView setTableViewActivityIndicatorViewIsShow:YES];
    
    NSString *searchString = self.searchField.text;
    NSString *HTXZ = @"";
    NSString *HTZT = @"";
    NSString *FFZT = @"";
    NSString *SHZT = @"";
    
    if (self.HTXZSegmente.selectedSegmentIndex != 0) {
        //合同性质=''--1:正式合同;2:临时合同;3:现金合同;
        HTXZ = [NSString stringWithFormat:@"%ld",self.HTXZSegmente.selectedSegmentIndex];
    }
    
    if (self.HTZTSegmente.selectedSegmentIndex != 0){
        //合同状态=''--1:待授权;2:已授权;3:已终止
        HTZT = [NSString stringWithFormat:@"%ld",self.HTZTSegmente.selectedSegmentIndex];
    }
    
    if (self.FFZTSegmente.selectedSegmentIndex != 0){
        //分发状态=''--0:未分发;1:已分发
        FFZT = [NSString stringWithFormat:@"%ld",self.FFZTSegmente.selectedSegmentIndex - 1];
    }
    
    if (self.SHZTSegmente.selectedSegmentIndex != 0){
        //审核状态='' --1:未审核;2:已审核
        SHZT = [NSString stringWithFormat:@"%ld",self.SHZTSegmente.selectedSegmentIndex];
    }
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_HTLB_LIST_20170117"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"起始条数" value:state];
    [content addParameterKey:@"结束条数" value:end];
    [content addParameterKey:@"合同性质" value:HTXZ];
    [content addParameterKey:@"审核状态" value:HTZT];
    [content addParameterKey:@"合同状态" value:FFZT];
    [content addParameterKey:@"分发状态" value:SHZT];
    [content addParameterKey:@"客户编号" value:@""];
    [content addParameterKey:@"检索条件" value:searchString];
    [content addParameterKey:@"合同ID" value:@""];
    
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        if(isReresh) [self.tableView setTableViewActivityIndicatorViewIsShow:NO];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(isReresh) [self.resultData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.resultData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
            [self setupRefresh];
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
    
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:0];
    NSNumber *endNumber = [NSNumber numberWithInteger:10];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count + 1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 10];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return @"";
    } else {
        return @" 消息搜索结果";
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierOne = @"MTContractListViewCell";
    MTContractListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
    if (!cell)
        cell = [[MTContractListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
    
    NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    cell.HTBHLabel.text = [model objectFormatStringForKey:@"合同编号" defaults:@"未知"];
    cell.HTMCLabel.text = [model objectFormatStringForKey:@"合同名称" defaults:@"未知"];
    cell.HTXZLabel.text = [model objectFormatStringForKey:@"合同性质" defaults:@"未知"];
    cell.LJFLLabel.text = [model objectFormatStringForKey:@"合同总量" format:@"累计%@方" defaults:@"未知"];
    
    //cell.HTJDLabel.text = [model objectFormatStringForKey:@"完成进度" format:@"%@%%" defaults:@"未知"];
    cell.HTJDLabel.text = [model objectFormatFloatStringForKey:@"完成进度" retain:1 format:@"%@%%"];
    cell.threeLabel.text = [model objectFormatStringForKey:@"业务人员" defaults:@"未知"];
    cell.fourLabel.text = [model objectFormatStringForKey:@"签订日期" defaults:@"未知"];
    cell.rightFourLabel.text = [model objectFormatStringForKey:@"合同状态" defaults:@"未知"];
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 82;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    
    MTCContractDetailViewController *viewController = [[MTCContractDetailViewController alloc] initWithModel:model isAllowOperate:YES];
    viewController.backResultDelagate = self;
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void) backResultDataKey:(id)key dataValue:(id)backValue
{
    //删除合同
    if (key && backValue && [key isEqualToString:@"Delete"]) {
        [self.resultData removeObject:backValue];
        [self.tableView reloadData];
        
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"Check"]){
        //合同审核
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"Modif"]){
        //合同修改
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"AuthContract"]){
        //合同授权
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        if(self.segmentActionState == 2){
            [self.resultData removeObject:originalArray[0]];
        } else {
            NSInteger index = [self.resultData indexOfObject:originalArray[0]];
            if(index > self.resultData.count){
                [self.resultData insertObject:originalArray[1] atIndex:0];
            } else {
                [self.resultData removeObjectAtIndex:index];
                [self.resultData insertObject:originalArray[1] atIndex:index];
            }
        }
        
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"StopContract"]){
        //合同终止
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        if(self.segmentActionState == 1){
            [self.resultData removeObject:originalArray[0]];
        } else {
            NSInteger index = [self.resultData indexOfObject:originalArray[0]];
            if(index > self.resultData.count){
                [self.resultData insertObject:originalArray[1] atIndex:0];
            } else {
                [self.resultData removeObjectAtIndex:index];
                [self.resultData insertObject:originalArray[1] atIndex:index];
            }
        }
        
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"Distribute"]){
        //合同分发
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
    }
    
}

@end
